package com.pi.shisan.component.util;

/**
 * 提取ArrayList精华，提升clear效率
 * 不使用包装类，直接使用int基本类型
 * 此类用于记录上一次绘制的点坐标
 * 不是线程安全的
 */
public class FastIntList {

    private int[] arr;
    private int pos;

    public FastIntList() {
        arr = new int[10];
    }

    public FastIntList(int size) {
        if (size <= 0) {
            throw new RuntimeException("unsupport size");
        }
        arr = new int[size];
    }

    public void add(int num) {
        int[] arr = this.arr;
        if (pos >= arr.length) {
            int newLen = (int)(arr.length * 1.5D);
            if (newLen == arr.length) {
                newLen+= 1;
            }
            int[] newArr = new int[newLen];
            System.arraycopy(arr, 0, newArr, 0, arr.length);
            this.arr = arr = newArr;
        }
        arr[pos ++] = num;
    }

    public void clear() {
        this.pos = 0;
    }

    public void forEach(FastListConsumer consumer) {
        final int[] arr = this.arr;
        for (int i = 0; i < pos; i++) {
            consumer.accept(arr[i]);
        }
    }

    public interface FastListConsumer {
        void accept(int num);
    }

}
